import pickle
import Configurable
import G
from Config import width, height
import Ship

class Save(object):
   __slots__ = ('campaign',
                'levelindex',
                'ship',
                'shipname',
                'money',
                'score',
                'weapons',
                'shield',
                'generator')
   
   def __init__(self, campaign, levelindex, ship):
      self.campaign = campaign.name
      self.levelindex = levelindex
      self.shipname = ship.name
      self.money = ship.money
      self.score = ship.score
      self.weapons = list()
      for w in ship.weapons:
         if w is not None:
            self.weapons.append((w.name, w.level))
         else:
            self.weapons.append(None)
      if ship.shield is not None:
         self.shield = ship.shield.name
      else:
         self.shield = None
      if ship.generator is not None:
         self.generator = ship.generator.name
      else:
         self.generator = None
   
   @classmethod
   def load(cls, filename):
      save = pickle.load(open(filename, 'r'))
      save.ship = Ship.spawn(G.ships[save.shipname], (width/2, 3*height/4), friendly=True)
      save.ship.money = save.money
      save.ship.score = save.score
      for i, w in enumerate(save.weapons):
         if w is not None:
            weapon = Configurable.instantiate(G.items[w[0]])
            save.ship.equip_weapon((weapon, w[1], i))
      if save.shield is not None:
         save.ship.equip_item(Configurable.instantiate(G.items[save.shield]))
      if save.generator is not None:
         save.ship.equip_item(Configurable.instantiate(G.items[save.generator]))
      return save
   
   def save(self, filename):
      pickle.dump(self, open(filename, 'w'), -1)
